/*
 * Copyright 2024-2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.cloud.ai.service.semantic;

import com.alibaba.cloud.ai.dto.SemanticModelAddDTO;
import com.alibaba.cloud.ai.entity.AgentDatasource;
import com.alibaba.cloud.ai.entity.SemanticModel;
import com.alibaba.cloud.ai.mapper.AgentDatasourceMapper;
import com.alibaba.cloud.ai.mapper.SemanticModelMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class SemanticModelServiceImpl implements SemanticModelService {

	private final SemanticModelMapper semanticModelMapper;

	private final AgentDatasourceMapper agentDatasourceMapper;

	@Override
	public List<SemanticModel> getAll() {
		return semanticModelMapper.selectAll();
	}

	@Override
	public List<SemanticModel> getEnabledByAgentId(Long agentId) {
		return semanticModelMapper.selectEnabledByAgentId(agentId);
	}

	@Override
	public List<SemanticModel> getByAgentIdAndTableNames(Integer agentId, List<String> tableNames) {
		Integer datasourceId = findDatasourceIdByAgentId(agentId);

		if (datasourceId == null || tableNames == null || tableNames.isEmpty()) {
			return List.of();
		}

		return semanticModelMapper.selectByDatasourceIdAndTableNames(datasourceId, tableNames);
	}

	@Override
	public SemanticModel getById(Long id) {
		return semanticModelMapper.selectById(id);
	}

	@Override
	public void addSemanticModel(SemanticModel semanticModel) {
		semanticModelMapper.insert(semanticModel);
	}

	@Override
	public boolean addSemanticModel(SemanticModelAddDTO dto) {
		// 根据agentId查询关联的datasourceId
		Integer datasourceId = findDatasourceIdByAgentId(dto.getAgentId());

		// 转换DTO为Entity
		SemanticModel semanticModel = SemanticModel.builder()
			.agentId(dto.getAgentId())
			.datasourceId(datasourceId)
			.tableName(dto.getTableName())
			.columnName(dto.getColumnName())
			.businessName(dto.getBusinessName())
			.synonyms(dto.getSynonyms())
			.businessDescription(dto.getBusinessDescription())
			.columnComment(dto.getColumnComment())
			.dataType(dto.getDataType())
			.status(1) // 默认启用状态
			.build();

		// 保存到数据库
		semanticModelMapper.insert(semanticModel);

		return true;
	}

	/**
	 * 根据agentId查找关联的datasourceId 如果有多个数据源，返回第一个启用的数据源
	 */
	private Integer findDatasourceIdByAgentId(Integer agentId) {
		List<AgentDatasource> agentDatasources = agentDatasourceMapper.selectByAgentId(agentId);

		if (agentDatasources.isEmpty()) {
			throw new RuntimeException("No datasource found for Agent ID " + agentId);
		}

		// 优先返回启用的数据源
		for (AgentDatasource ad : agentDatasources) {
			if (ad.getIsActive() != null && ad.getIsActive() == 1) {
				return ad.getDatasourceId();
			}
		}

		// 如果没有启用的数据源，返回第一个
		return agentDatasources.get(0).getDatasourceId();
	}

	@Override
	public void enableSemanticModel(Long id) {
		semanticModelMapper.enableById(id);
	}

	@Override
	public void disableSemanticModel(Long id) {
		semanticModelMapper.disableById(id);
	}

	@Override
	public List<SemanticModel> getByAgentId(Long agentId) {
		return semanticModelMapper.selectByAgentId(agentId);
	}

	@Override
	public List<SemanticModel> search(String keyword) {
		return semanticModelMapper.searchByKeyword(keyword);
	}

	@Override
	public void deleteSemanticModel(Long id) {
		semanticModelMapper.deleteById(id);
	}

	@Override
	public void updateSemanticModel(Long id, SemanticModel semanticModel) {
		semanticModel.setId(id);
		semanticModelMapper.updateById(semanticModel);
	}

}
